package cn.hanyi;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.jms.*;

/**
 * Created by Administrator on 2018/1/15 0015.
 */
@Service
@EnableScheduling
public class Producer {
    @Autowired// 也可以注入JmsTemplate，JmsMessagingTemplate对JmsTemplate进行了封装
    private JmsTemplate jmsQueueTemplate;


    // 发送消息，destination是发送到的队列，message是待发送的消息
//    public void sendMessage(Destination destination, final String message){
//        jmsTemplate.convertAndSend(destination, message);
//    }
//    @Scheduled(fixedDelay=3000)//每3s执行1次
//    public void send() {
//        this.jmsMessagingTemplate.convertAndSend(this.queue, "hi,activeMQ");
//    }
    /**
     * 发送原始消息 Message
     */
//    @Scheduled(cron = "*/3 * * * * *")//每3s执行1次
    public void send(){
        jmsQueueTemplate.send("queue1", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage("我是原始消息");
            }
        });
        jmsQueueTemplate.send("queue2", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage("我是你爸爸");
            }
        });
    }

    /**
     * 发送消息自动转换成原始消息
     */
    public void convertAndSend(){

        jmsQueueTemplate.convertAndSend("queue1", "我是自动转换的消息");

    }
}
